<style lang="scss">
  @import "../../styles/base";

  .container {

    background-color: #f5f5f5;
    height: 100vh;
    .connect-tip {
      padding-top: pxToRem(200);
      padding-bottom: pxToRem(60);
      font-size: pxToRem(48);
      color: #1f1f1f;
      text-align: center;
    }
    .mt-100 {
      padding-top: pxToRem(30);
    }
    .android-tip {
      padding-left: pxToRem(50);
      padding-right: pxToRem(50);
      padding-top: pxToRem(30);
      font-size: pxToRem(40);
      color: #1f1f1f;
      text-align: center;
    }
    .progress-wrap {
      position: relative;
      margin: pxToRem(200) auto;
      width: 270rpx;
      height: 270rpx;
    }
    .progress {
      @include middle-center();
      width: 260rpx;
      height: 260rpx;
      border: 5rpx dotted $main-color;
      border-radius: 50%;
      box-sizing: border-box;
    }
    .progress-value {
      @include middle-center();
      width: 250rpx;
      height: 250rpx;
      line-height: 250rpx;
      font-size: pxToRem(130);
      color: $main-color;
      text-align: center;
      z-index: 1000;
    }
  }
  .total-time {
    font-size: pxToRem(100);
    font-weight: bold;
    padding-top: pxToRem(30);
    text-align: center;
  }
  .active-bar {
    @include middle-center();
    width: 265rpx;
    height: 265rpx;
    z-index: 100;
  }
</style>
<template>
  <div class="container" :class="isIphoneX ? 'iphoneX':''">
    <div class="connect-tip">尝试与设备建立链接</div>
    <div class="progress-wrap">
      <div class="progress"></div>
      <div class="progress-value">{{percentage}}%</div>
      <canvas class="active-bar" canvas-id="progressCanvas"></canvas>
    </div>
    <div class="connect-tip mt-100">
      正在努力地链接智能设备,请耐心等待!<br/>
      设备链接中<br/>
      ......
    </div>
    <div class="total-time">{{totalTime}}S</div>
    <div class="android-tip" v-if="isAndroid">设备网络配置过程中，出现手机无法链接网络情况为正常现象，请耐心等待</div>
  </div>
</template>

<script>
  import md5 from 'md5'
  import { APP_SECRET } from '../../config'

  export default {
    data() {
      return {
        isIphoneX: /iPhone X/.test(App.systemInfo.model),
        process: 0,
        isAndroid: !/iOS/.test(App.systemInfo.system),
        totalTime: /iOS/.test(App.systemInfo.system) ? 120 : 90,
        isIos: /iOS/.test(App.systemInfo.system),
        percentage: 0,
        maxTime: /iOS/.test(App.systemInfo.system) ? 120 : 90
      }
    },
    components: {},
    methods: {
      bindMac(mac, productKey) {
        const timestamp = parseInt(Date.now() / 1000);
        return wx.request({
          url: '/app/bind_mac',
          method: 'POST',
          data: {
            product_key: productKey,
            mac: mac,
          },
          header: {
            'X-Gizwits-User-token': App.userInfo.token,
            'X-Gizwits-Timestamp': timestamp,
            'X-Gizwits-Signature': md5(APP_SECRET + timestamp).toLowerCase(),
          },
        })
      },
      async checkOnline(did) {
        console.log('检查设备状态')
        const deviceListResult = await wx.request({
            url: '/app/bindings',
            data: {
              show_disabled: 0,
              limit: 40,
              skip: 0,
            },
            header: {
              'X-Gizwits-User-token': App.userInfo.token,
            }
          })
          console.info(deviceListResult)
          const flag = deviceListResult.devices.some(device => {
            return device.did === did && device.is_online;
          })
          if (flag) {
            this.progressTask && clearTimeout(this.progressTask)
            wx.hideLoading();
            wx.redirectTo({ url: '/pages/config-success/main' })
          }else{
            setTimeout(() => {
              this.checkOnline(did)
            }, 3000)
          }
      },
      async startBind(result) {
        console.log('开始绑定')
        const bindResult = await this.bindMac(result.MAC, result.PK);
        console.log('绑定结果')
        console.info(bindResult)
        if (bindResult.did) {
          App.currentDevice = bindResult;
          this.checkOnline(bindResult.did);
        }else{
          setTimeout(() => {
            this.startBind(result)
          }, 3000)
        }
      },
      startProgress() {
        const ctx = wx.createCanvasContext('progressCanvas')
        const radius = 132.5 * App.systemInfo.screenWidth / 750;
        const width = 5 * App.systemInfo.screenWidth / 750;
        const angle = (2 * (this.maxTime - this.totalTime) / this.maxTime - 0.5) * Math.PI;
        this.percentage < 91 && this.percentage++;
        if (this.totalTime === 0) {
          clearTimeout(this.configNetworkTask)
          clearTimeout(this.progressTask);
          wx.redirectTo({ url: '/pages/config-fail/main' })
        } else {
          this.totalTime--;
          this.progressTask = setTimeout(() => {
             this.startProgress();
          }, 1000)
          ctx.beginPath()
          ctx.arc(radius, radius, radius - width, -0.5 * Math.PI, angle)
          ctx.setStrokeStyle('#fece00');
          ctx.setLineWidth(width);
          ctx.stroke()
          ctx.draw()
        }
      },
      async configNetwork() {
        if(this.isHide){
          return false;
        }
        const result = await wx.request({
          url: 'https://www.granwin.cn',
          method: 'POST',
          data: {
            CID: 30005,
            PL: {
              SSID: App.currentForm && App.currentForm.ssid,
              Password: App.currentForm && App.currentForm.password,
            }
          },
        })
        console.log('配网结果:', result)
        if (result.MAC) {
          console.log('配网成功')
          clearTimeout(this.configNetworkTask)
          if (!this.isIos && !this.isConnecting) {
            this.isConnecting = true;
            console.log('开始切回原始WiFi,SSID:'+App.currentForm.ssid+',password:'+App.currentForm.password)
            wx.connectWifi({
              SSID: App.currentForm && App.currentForm.ssid,
              password: App.currentForm && App.currentForm.password,
              complete: () => {
                console.log('切换成功, 开始绑定..')
                this.isConnecting = false;
                this.startBind(result)
              }
            })
          }else{
            this.startBind(result)
          }
        } else {
          console.log('开始重试配网')
          const networkType = await wx.getNetworkType()
          let connectResult = await wx.getConnectedWifi();
          if (!this.isIos && (networkType.networkType != 'wifi' ||
            connectResult.wifi.SSID != App.currentSSID) && !this.isConnecting) {
            console.log('开始切回设备WiFi,SSID:'+App.currentSSID)
            this.isConnecting = true;
            wx.connectWifi({
              SSID: App.currentSSID,
              password: '',
              complete: () => {
                console.log('切换结果成功，继续配网')
                this.isConnecting = false;
                this.configNetwork();
              }
            })
          }else {
            this.configNetworkTask = setTimeout(() => {
              this.configNetwork();
            }, 5000)
          }
        }
      }
    },
    onHide(){
      this.isHide = true;
      this.progressTask && clearTimeout(this.progressTask)
      this.configNetworkTask && clearTimeout(this.configNetworkTask)
    },
    onUnload() {
      console.info('onUnload....')
      this.totalTime = this.maxTime;
      this.percentage = 0;
    },
    async onShow() {
      if (!App.userInfo) {
        await App.fetchLogin();
      }
      this.isHide = false;
      console.info(this.totalTime)
      this.startProgress();
      this.configNetwork();
    },

  }
</script>
